#include <QDebug>

#include "rssleaf.h"
#include "qrssglobals.h"

RssLeaf::RssLeaf():m_state( eNew )
{
}

RssLeaf::~RssLeaf()
{
	
}

QString RssLeaf::getNextItem( const QString& stream, bool newLine )
{
	static int i = 0;
	static int j = 0;

	if(  newLine )
	{
		i = 0;
		j = 0;
	}

	QString res;

	if (( j = stream.indexOf( ITEMSEPARATOR, j )) != -1 )
	{
		res = stream.mid( i, j - i );
		j+=ITEMSEPARATORLENGTH;
		i = j;
	}
	else
		qDebug() << "getNextItem failed";
	return res;
}

void RssLeaf::internalize( const QString& line )
{
	bool ok = false;
	m_name = getNextItem( line, true );
	QString state( getNextItem( line ));
	m_state = ( ItemState )state.toInt( &ok );
	if( !ok )
	{
		qDebug() << "state:: incorrect state passed";
		m_state = eNew;
	}
	else
	{
		ok = false;
		if( m_state == eNew )
			m_state = eUnreaded;
	}

	state = getNextItem( line );
	int count = state.toInt( &ok );
	if( !ok )
		count = 0;

	QString key, value;

	for( int i = 0; i < count; ++i )
	{
		key = getNextItem( line );
		value = getNextItem( line );
		m_itemData.insert( key, value );
	}
}

void RssLeaf::externalize( QTextStream& stream )
{	
	stream << m_name << ITEMSEPARATOR;
	
	stream << ( int ) m_state << ITEMSEPARATOR;
	stream << m_itemData.count() << ITEMSEPARATOR;

	if( m_itemData.count() > 0 )
	{
		QRssLeafData::iterator it = m_itemData.begin();
		while ( it != m_itemData.end() )
		{
			stream << it.key() << ITEMSEPARATOR;
			stream << it.value() << ITEMSEPARATOR;
			++it;
		}
	}
	else
	{
		stream << 0 << ITEMSEPARATOR;
	}
	stream << "\n";
}

void RssLeaf::operator>>( QTextStream& stream )
{
	//externalize( stream );
}

void RssLeaf::operator<<( QTextStream& stream )
{
	//internalize( stream );
}

void RssLeaf::addData( const QString& key, const QString& value )
{
	m_itemData.insert( key, value );
}

QString RssLeaf::value( const QString& key ) const
{
	return m_itemData[key];
}
